const encoder = new TextEncoder();
const decoder = new TextDecoder("utf-8");
const re = /\r\n|\n|\r/m;

export function* readLine(buffer: ArrayBuffer, offset: number) {
  const size = buffer.byteLength;

  let index = 0;

  for (;;) {
    if (index >= size) break;

    let bytes = buffer.slice(index, index + offset);
    let chunk = decoder.decode(bytes);
    const match = re.exec(chunk);

    if (match) {
      chunk = chunk.substring(0, match.index);
      index = index + encoder.encode(chunk).byteLength + match[0].length;
    } else {
      if (index + offset >= size) {
        index = size;
      } else {
        throw { error: `offset length ${offset} is too small.`, chunk, index };
      }
    }

    yield { line: chunk, index };
  }
}
